from django.contrib.auth import password_validation
from django.contrib.auth.forms import UsernameField
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import ValidationError
from django import forms
from django.forms import ModelForm

from itmopets.models import Profile, Pet


class NewUserCreationForm(UserCreationForm):

    password_requirements = """
    <ul><li>Ваш пароль не может быть слишком похож на другую личную информацию.</li>
    <li>Ваш пароль должен содержать как минимум 8 символов.</li>
    <li>Ваш пароль не может быть часто используемым паролем (вроде qwerty или test).</li>
    <li>Ваш пароль не может быть полностью цифровым.</li></ul>
    """

    error_messages = {
        "password_mismatch": "Пароли не совпадают",
    }
    password1 = forms.CharField(
        label="Пароль",
        strip=False,
        widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
        help_text=password_requirements,
    )
    password2 = forms.CharField(
        label="Повторите пароль",
        widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
        strip=False,
        help_text="Введите пароль еще раз, для подтверждения.",
    )

    birthdate = forms.DateField(label='Дата рождения', widget=forms.SelectDateWidget(years=range(1900, 2020)))

    contact = forms.IntegerField(label='Контактный телефон', widget=forms.TextInput(attrs={'placeholder': '+7 (999) 999-99-99'}))

    class Meta:
        model = User
        fields = ("username", 'first_name', "last_name", "contact", "birthdate")
        field_classes = {"username": UsernameField}
        labels = {
            "username": "Логин",
            'contact': "Контактный телефон",
            "birthdate": "Дата рождения",
            'first_name': "Имя",
            'last_name': "Фамилия",
        }
        help_texts = {
            "username": ""
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self._meta.model.USERNAME_FIELD in self.fields:
            self.fields[self._meta.model.USERNAME_FIELD].widget.attrs[
                "autofocus"
            ] = True

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise ValidationError(
                self.error_messages["password_mismatch"],
                code="password_mismatch",
            )
        return password2

    def _post_clean(self):
        super()._post_clean()
        # Validate the password after self.instance is updated with form data
        # by super().
        password = self.cleaned_data.get("password2")
        if password:
            try:
                password_validation.validate_password(password, self.instance)
            except ValidationError as error:
                self.add_error("password2", error)

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class EditProfileForm(ModelForm):
    class Meta:
        model = User
        fields = (
            'email',
            'first_name',
            'last_name'
        )


class ProfileForm(ModelForm):
    class Meta:
        model = Profile
        fields = ('contact', 'date_of_birth', 'sex', 'address', 'status', "avatar")
        labels = {
            "contact": "Контактный телефон",
            'sex': "Пол",
            "date_of_birth": "Дата рождения",
            "address": "Адрес",
            "status": "Статус",
            "avatar": "Аватар"
        }


class PetForm(ModelForm):
    class Meta:
        model = Pet
        fields = ('name', "breed", "coat", "coat_variety", "date_of_birth", "sex", "size", "pet_image", "allergy", "disease", "chip_number", "chipping_date", "location_of_chip", "tattoo_number", "locator_data", "distinctive_marks", "extra_info")
        labels = {
            "name": "Имя",
            "breed": "Порода",
            "coat": "Шерсть",
            "coat_variety": "Тип шерсти",
            "date_of_birth": "Дата рождения",
            "sex": "Пол",
            "size": "Размер",
            "pet_image": "Фото",
            "allergy": "Аллергии",
            "disease": "Болезни",
            "chip_number": "Номер чипа",
            "chipping_date": "Дата чипирования",
            "location_of_chip": "Место чипирования",
            "tattoo_number": "Номер тату",
            "locator_data": "Данные локатора",
            "distinctive_marks": "Особые отметки",
            "extra_info": "Дополнительная информация"
        }
        widgets = {
            'date_of_birth': forms.SelectDateWidget(years=range(1900, 2020)),
            'chipping_date': forms.SelectDateWidget(years=range(1900, 2020)),
        }

    def __init__(self, user, *args, **kwargs):
        super(PetForm, self).__init__(*args, **kwargs)
        self.user = user

    def save(self, commit=True, *args, **kwargs):
        pet = super().save(commit=False)
        pet.owner = self.user
        if commit:
            pet.save()
        return pet

